﻿namespace FFF.Test.Util.Configuration
{
    using System.Collections.Concurrent;
    using Abp.Extensions;
    using Microsoft.Extensions.Configuration;

    /// <summary>
    /// 用于取appsetting.json文件的内容
    /// </summary>
    public static class AppConfigurationHelper
    {
        private static readonly ConcurrentDictionary<string, IConfigurationRoot> ConfigurationCache;

        /// <summary>
        /// Initializes static members of the <see cref="AppConfigurationHelper"/> class.
        /// 静态构造存储
        /// </summary>
        static AppConfigurationHelper() => ConfigurationCache = new ConcurrentDictionary<string, IConfigurationRoot>();

        /// <summary>
        /// 获取配置
        /// </summary>
        /// <param name="path">json文件所在的路径</param>
        /// <param name="environmentName">加环境的名称</param>
        /// <returns>配置集合</returns>
        public static IConfigurationRoot Get(string path, string environmentName = null)
        {
            var cacheKey = path + "#" + environmentName;
            return ConfigurationCache.GetOrAdd(
                cacheKey,
                _ => BuildConfiguration(path, environmentName)
            );
        }

        /// <summary>
        /// json路径
        /// </summary>
        /// <param name="path">jsong路径</param>
        /// <param name="environmentName">json别名</param>
        /// <returns>jison配置</returns>
        private static IConfigurationRoot BuildConfiguration(string path, string environmentName = null)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(path)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

            if (!environmentName.IsNullOrWhiteSpace())
            {
                builder = builder.AddJsonFile($"appsettings.{environmentName}.json", optional: true);
            }

            builder = builder.AddEnvironmentVariables();

            return builder.Build();
        }
    }
}
